package com.kaifamiao.dispatch;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;

@WebServlet( "/file/upload" )
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    // 记录文件保存路径的字段
    private File store ;

    @Override
    public void init() throws ServletException {
        // FileUploadServlet类 继承 HttpServlet类
        // HttpServlet类 继承了 GenericServlet类
        // GenericServlet类 ServletConfig 接口
        // 在 ServletConfig 接口中定义了 getServletContext
        ServletContext sc = this.getServletContext();
        // 获取 ServletContext 初始化参数
        String location = sc.getInitParameter( "location" );
        // 根据获取到的路径创建File实例
        store = new File( location );
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding( "UTF-8" );
        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html;charset=UTF-8" );
        // 获得可以向"响应对象"中输出字符数据的打印流
        PrintWriter out = response.getWriter();

        // <input type="file" name="upfile" >
        Part part = request.getPart( "upfile" );
        if( part == null ) {
            out.println( "<p style=\"color:red;\">上传失败: 可能是文件选择组件的name属性值不是upfile</p>" );
            out.println( "<a href=\"/upload.html\">返回上传页面</a>" );
            return ;
        }

        String filename = part.getSubmittedFileName(); // Servlet 3.1 ( Tomcat 7.X 不支持 )
        if( filename == null || filename.trim().isEmpty() ) {
            out.println( "<p style=\"color:red;\">请先选择文件后再提交</p>" );
            out.println( "<a href=\"/upload.html\">返回上传页面</a>" );
            return ;
        }

        InputStream input = part.getInputStream();

        File target = new File( store , filename );
        OutputStream output = new FileOutputStream( target );
        int n ;
        byte[] buffer = new byte[ 1 << 20 ];
        while( ( n = input.read( buffer ) ) != -1 ){
            output.write( buffer , 0 , n );
        }
        output.close();
        input.close();
        out.println( "<p style=\"color:green;\">文件[" + filename + "]上传成功</p>" );
        // 若文件上传成功则去往文件列表
        response.sendRedirect( "/file/list" );
    }

    @Override
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException {
        throw new IllegalStateException( "不支持GET方式上传文件" );
    }

}
